{% extends "admin/base.html" %}

{% block title %}分类管理{% endblock %}

{% block content %}
<div class="categories-container">
    <!-- 页面头部 -->
    <div class="categories-header">
        <h1><i class="fas fa-folder"></i> 分类管理</h1>
        <div class="categories-actions">
            <button class="bg-blue-500 text-white px-4 py-2 rounded-md no-underline font-medium text-sm transition-all duration-300 inline-flex items-center gap-2 hover:bg-blue-600 hover:text-white hover:no-underline" onclick="showAddCategoryModal()">
                <i class="fas fa-plus"></i>
                新建分类
            </button>
        </div>
    </div>
    
    <!-- 筛选和搜索区域 -->
    <div class="categories-filters">
        <div class="filter-group">
            <label for="parent-filter">父分类筛选</label>
            <select id="parent-filter">
                <option value="">全部分类</option>
                <option value="top">顶级分类</option>
            </select>
        </div>
        
        <div class="filter-group">
            <label for="search-input">搜索分类</label>
            <input type="text" id="search-input" placeholder="输入分类名称或描述关键词...">
        </div>
        
        <button class="btn-filter" onclick="applyFilters()">
            <i class="fas fa-search"></i>
            搜索
        </button>
        
        <button class="btn-reset" onclick="resetFilters()">
            <i class="fas fa-undo"></i>
            重置
        </button>
    </div>
    
    <!-- 分类列表 -->
    <div class="table-responsive">
        <table class="categories-table">
            <thead>
                <tr>
                    <th style="width: 30%;">分类信息</th>
                    <th style="width: 30%;">描述</th>
                    <th style="width: 15%;">父分类</th>
                    <th style="width: 8%;">排序</th>
                    <th style="width: 10%;">创建时间</th>
                    <th style="width: 7%;">操作</th>
                </tr>
            </thead>
            <tbody id="categories-tbody"></tbody>
        </table>
    </div>
    
</div>

<!-- 分页 -->
<div class="mt-0">
    <div class="bg-white rounded-b-lg shadow-md p-6">
        <div class="flex items-center justify-between">
            <!-- 分页信息 -->
            <div class="text-sm text-gray-600" id="pagination-info">暂无记录</div>
            
            <!-- 分页导航 -->
            <nav class="flex items-center space-x-1" id="pagination-nav"></nav>
        </div>
    </div>
</div>

<!-- 添加/编辑分类模态框 -->
<div id="category-modal" class="modal-overlay" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modal-title">新建分类</h2>
            <button class="modal-close" onclick="hideCategoryModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body">
            <form id="category-form">
                <input type="hidden" id="category-id" name="id">
                <input type="hidden" id="category-parent-id" name="parent_id">
                
                <div class="form-group">
                    <label for="category-name">分类名称 *</label>
                    <input type="text" id="category-name" name="name" required>
                </div>
                
                
                <div class="form-group">
                    <label for="category-description">分类描述</label>
                    <textarea id="category-description" name="description" rows="3"></textarea>
                </div>
                
                <div class="form-group">
                    <label for="category-color">分类颜色</label>
                    <div class="color-picker">
                        <input type="color" id="category-color" name="color" value="#007bff">
                        <div class="color-presets">
                            <div class="color-preset" data-color="#007bff" style="background-color: #007bff"></div>
                            <div class="color-preset" data-color="#28a745" style="background-color: #28a745"></div>
                            <div class="color-preset" data-color="#dc3545" style="background-color: #dc3545"></div>
                            <div class="color-preset" data-color="#ffc107" style="background-color: #ffc107"></div>
                            <div class="color-preset" data-color="#17a2b8" style="background-color: #17a2b8"></div>
                            <div class="color-preset" data-color="#6f42c1" style="background-color: #6f42c1"></div>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="category-parent">父分类</label>
                    <select id="category-parent" name="parent_id">
                        <option value="">无（顶级分类）</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="category-sort">排序</label>
                    <input type="number" id="category-sort" name="sort_order" value="0" min="0">
                    <small>数字越小排序越靠前</small>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn-secondary" onclick="hideCategoryModal()">取消</button>
            <button type="button" class="btn-primary" onclick="saveCategory()">保存</button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
/* 分类管理页面样式 - 与文章管理保持一致 */
.categories-container {
    background: #fff;
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    overflow: hidden;
    margin: 0;
}

.categories-header {
    padding: 1.5rem 2rem;
    border-bottom: 1px solid #e1e8ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.categories-header h1 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.25rem;
    font-weight: 600;
}

.categories-actions {
    display: flex;
    gap: 1rem;
    align-items: center;
}

.btn-primary {
    background: #007bff;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 500;
    font-size: 0.875rem;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
}

/* 小尺寸按钮，与文章管理一致 */
.btn-small {
    padding: 0.375rem 0.75rem;
    font-size: 0.8125rem;
}

.btn-primary:hover {
    background: #0056b3;
    color: white;
    text-decoration: none;
}

/* 筛选和搜索区域 */
.categories-filters {
    padding: 1.5rem 2rem;
    background: #f8f9fa;
    border-bottom: 1px solid #e1e8ed;
    display: flex;
    gap: 1rem;
    align-items: center;
    flex-wrap: wrap;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.filter-group label {
    font-size: 0.875rem;
    font-weight: 500;
    color: #495057;
}

.filter-group select,
.filter-group input {
    padding: 0.5rem;
    border: 1px solid #ced4da;
    border-radius: 6px;
    font-size: 0.875rem;
    min-width: 150px;
}

.filter-group input {
    min-width: 200px;
}

.btn-filter {
    background: #007bff;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.875rem;
    transition: background 0.3s ease;
    align-self: flex-end;
}

.btn-filter:hover {
    background: #0056b3;
}

.btn-reset {
    background: #6c757d;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.875rem;
    transition: background 0.3s ease;
    align-self: flex-end;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-reset:hover {
    background: #5a6268;
}

/* 表格样式 */
.table-responsive {
    overflow-x: auto;
}

.categories-table {
    width: 100%;
    border-collapse: collapse;
}

.categories-table th {
    background: #f8f9fa;
    padding: 1rem;
    text-align: left;
    font-weight: 600;
    color: #495057;
    border-bottom: 2px solid #dee2e6;
    font-size: 0.875rem;
}

.categories-table td {
    padding: 1rem;
    border-bottom: 1px solid #f1f3f4;
    vertical-align: middle;
}

.categories-table tbody tr:hover {
    background: #f8f9fa;
}

.sub-category {
    background-color: #fafbfc;
}

.sub-category:hover {
    background-color: #f1f3f4;
}


.category-info {
    display: flex;
    flex-direction: column;
}

.category-name {
    margin: 0 0 0.25rem 0;
    font-size: 1rem;
    font-weight: 600;
    color: #333;
}

.sub-category-info .category-name {
    font-size: 0.875rem;
    font-weight: 500;
    color: #666;
}

.sub-categories-count {
    font-size: 0.75rem;
    color: #666;
    background-color: #e9ecef;
    padding: 0.125rem 0.5rem;
    border-radius: 12px;
    width: fit-content;
}

    border-radius: 4px;
    font-family: monospace;
    font-size: 0.75rem;
    color: #495057;
}

.category-description {
    font-size: 0.875rem;
    color: #666;
    line-height: 1.4;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.category-sort {
    font-weight: 500;
    color: #333;
}

.category-date {
    font-size: 0.875rem;
    color: #666;
}

.category-actions {
    display: flex;
    gap: 0.5rem;
}

.btn-action {
    padding: 0.375rem 0.75rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.875rem;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.btn-edit {
    background: #007bff;
    color: white;
}

.btn-edit:hover {
    background: #0056b3;
    color: white;
    text-decoration: none;
}

.btn-delete {
    background: #dc3545;
    color: white;
}

.btn-delete:hover {
    background: #c82333;
    color: white;
}

.empty-state {
    text-align: center;
    padding: 4rem 2rem;
    color: #666;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    color: #ccc;
}

.empty-state h3 {
    margin: 0 0 0.5rem 0;
    font-size: 1.25rem;
}

.empty-state p {
    margin: 0 0 2rem 0;
    font-size: 1rem;
}


/* 模态框样式 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
    width: 90%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1.5rem 2rem;
    border-bottom: 1px solid #e9ecef;
}

.modal-header h2 {
    margin: 0;
    font-size: 1.25rem;
    color: #333;
}

.modal-close {
    background: none;
    border: none;
    font-size: 1.25rem;
    color: #666;
    cursor: pointer;
    padding: 0.5rem;
    border-radius: 4px;
    transition: background-color 0.2s ease;
}

.modal-close:hover {
    background-color: #f8f9fa;
}

.modal-body {
    padding: 2rem;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 1rem;
    padding: 1.5rem 2rem;
    border-top: 1px solid #e9ecef;
}

.form-group {
    margin-bottom: 1.5rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #333;
}

.form-group input,
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 0.875rem;
    transition: border-color 0.2s ease;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
    outline: none;
    border-color: #007bff;
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.form-group small {
    display: block;
    margin-top: 0.25rem;
    font-size: 0.75rem;
    color: #666;
}

.color-picker {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.color-picker input[type="color"] {
    width: 50px;
    height: 40px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.color-presets {
    display: flex;
    gap: 0.5rem;
}

.color-preset {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    cursor: pointer;
    border: 2px solid transparent;
    transition: all 0.2s ease;
}

.color-preset:hover {
    transform: scale(1.1);
}

.color-preset.active {
    border-color: #333;
}

.btn-primary, .btn-secondary {
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 4px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-primary {
    background-color: #007bff;
    color: white;
}

.btn-primary:hover {
    background-color: #0056b3;
}

.btn-secondary {
    background-color: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background-color: #545b62;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
// Client-side categories management (fetch + render)
let allCategories = [];
let filteredCategories = [];
let currentPage = 1;
const perPage = 10;

function formatDate(iso) {
    if (!iso) return '';
    try { return iso.slice(0, 10); } catch { return ''; }
}

async function fetchCategories() {
    const res = await fetch('/api/categories');
    const json = await res.json();
    if (!json.success) throw new Error('加载分类失败');
    allCategories = json.data || [];
}

function getParentName(id) {
    if (!id) return '顶级分类';
    const p = allCategories.find(c => c.id === id);
    return p ? p.name : '顶级分类';
}

function applyFilters() {
    const parentFilter = document.getElementById('parent-filter').value;
    const searchInput = document.getElementById('search-input').value.trim().toLowerCase();
    filteredCategories = allCategories.filter(c => {
        const hit = !searchInput || (c.name?.toLowerCase().includes(searchInput) || (c.description||'').toLowerCase().includes(searchInput));
        if (!hit) return false;
        if (!parentFilter) return true;
        if (parentFilter === 'top') return !c.parent_id;
        return String(c.parent_id||'') === String(parentFilter);
    });
    currentPage = 1;
    renderTable();
    renderPagination();
}

function resetFilters() {
    document.getElementById('parent-filter').value = '';
    document.getElementById('search-input').value = '';
    applyFilters();
}

function renderParentFilterOptions() {
    const select = document.getElementById('parent-filter');
    // keep first two options: '' and 'top'
    while (select.options.length > 2) select.remove(2);
    const tops = allCategories.filter(c => !c.parent_id);
    tops.forEach(c => {
        const opt = document.createElement('option');
        opt.value = c.id;
        opt.textContent = c.name;
        select.appendChild(opt);
    });
}

function renderParentSelectInModal(selected) {
    const select = document.getElementById('category-parent');
    while (select.options.length > 1) select.remove(1);
    allCategories.forEach(c => {
        const opt = document.createElement('option');
        opt.value = c.id;
        opt.textContent = c.name;
        select.appendChild(opt);
    });
    select.value = selected || '';
}

function renderTable() {
    const tbody = document.getElementById('categories-tbody');
    tbody.innerHTML = '';
    const start = (currentPage - 1) * perPage;
    const pageItems = filteredCategories.slice(start, start + perPage);
    if (pageItems.length === 0) {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td colspan="6" class="empty-state">
            <i class="fas fa-folder-open"></i>
            <h3>暂无分类</h3>
            <p>开始创建你的第一个分类吧！</p>
        </td>`;
        tbody.appendChild(tr);
        return;
    }
    for (const c of pageItems) {
        const tr = document.createElement('tr');
        tr.setAttribute('data-category-id', c.id);
        tr.setAttribute('data-parent-id', c.parent_id || '');
        tr.innerHTML = `
            <td>
                <div class="category-info">
                    <h3 class="category-name">${c.name}</h3>
                </div>
            </td>
            <td><div class="category-description">${c.description || '暂无描述'}</div></td>
            <td><span style="color:#6c757d;">${getParentName(c.parent_id)}</span></td>
            <td><span class="category-sort">${c.sort_order ?? 0}</span></td>
            <td><span class="category-date">${formatDate(c.created_at)}</span></td>
            <td>
                <div class="category-actions">
                    <button class="btn-action btn-edit" title="编辑" onclick="editCategory(${c.id})"><i class="fas fa-edit"></i></button>
                    <button class="btn-action btn-delete" title="删除" onclick="deleteCategory(${c.id})"><i class="fas fa-trash"></i></button>
                </div>
            </td>`;
        tbody.appendChild(tr);
    }
}

function renderPagination() {
    const info = document.getElementById('pagination-info');
    const nav = document.getElementById('pagination-nav');
    nav.innerHTML = '';
    const total = filteredCategories.length;
    if (total === 0) { info.textContent = '暂无记录'; return; }
    const start = (currentPage - 1) * perPage + 1;
    const end = Math.min(currentPage * perPage, total);
    info.textContent = `显示第 ${start} - ${end} 条，共 ${total} 条记录`;
    const pages = Math.ceil(total / perPage);
    const mkBtn = (html, disabled, onClick) => {
        const el = document.createElement(disabled ? 'span' : 'a');
        el.className = disabled ? 'px-3 py-2 text-gray-300 cursor-not-allowed' : 'px-3 py-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors';
        el.innerHTML = html;
        if (!disabled) el.addEventListener('click', onClick);
        return el;
    };
    nav.appendChild(mkBtn('<i class="fas fa-angle-double-left"></i>', currentPage === 1, () => { currentPage = 1; renderTable(); renderPagination(); }));
    nav.appendChild(mkBtn('<i class="fas fa-chevron-left"></i>', currentPage === 1, () => { currentPage--; renderTable(); renderPagination(); }));
    for (let p = 1; p <= pages; p++) {
        if (p === currentPage) {
            const span = document.createElement('span');
            span.className = 'px-3 py-2 bg-blue-600 text-white rounded-lg font-medium';
            span.textContent = String(p);
            nav.appendChild(span);
        } else {
            const a = document.createElement('a');
            a.className = 'px-3 py-2 text-gray-700 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors';
            a.textContent = String(p);
            a.addEventListener('click', () => { currentPage = p; renderTable(); renderPagination(); });
            nav.appendChild(a);
        }
    }
    nav.appendChild(mkBtn('<i class="fas fa-chevron-right"></i>', currentPage === pages, () => { currentPage++; renderTable(); renderPagination(); }));
    nav.appendChild(mkBtn('<i class="fas fa-angle-double-right"></i>', currentPage === pages, () => { currentPage = pages; renderTable(); renderPagination(); }));
}

// Modal helpers
function showAddCategoryModal() {
    document.getElementById('modal-title').textContent = '新建分类';
    document.getElementById('category-form').reset();
    document.getElementById('category-id').value = '';
    renderParentSelectInModal('');
    document.getElementById('category-modal').style.display = 'flex';
}

function editCategory(categoryId) {
    const c = allCategories.find(x => x.id === categoryId);
    if (!c) { Utils.notification.show('分类不存在', 'error'); return; }
    document.getElementById('modal-title').textContent = '编辑分类';
    document.getElementById('category-id').value = c.id;
    document.getElementById('category-name').value = c.name;
    document.getElementById('category-description').value = c.description || '';
    document.getElementById('category-color').value = c.color || '#007bff';
    document.getElementById('category-sort').value = c.sort_order ?? 0;
    renderParentSelectInModal(c.parent_id || '');
    document.getElementById('category-modal').style.display = 'flex';
}

function hideCategoryModal() {
    document.getElementById('category-modal').style.display = 'none';
}

async function deleteCategory(categoryId) {
    const c = allCategories.find(x => x.id === categoryId);
    if (!c) { Utils.notification.show('分类不存在', 'error'); return; }
    Utils.confirm.show(`确定要删除分类"${c.name}"吗？此操作不可恢复。`, async () => {
        try {
            const res = await fetch(`/api/categories/${categoryId}`, {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' }
            });
            const json = await res.json();
            if (json.success) { Utils.notification.show('分类删除成功', 'success'); await refreshData(); }
            else { Utils.notification.show(json.message || '删除失败', 'error'); }
        } catch (e) { Utils.notification.show('删除失败，请稍后重试', 'error'); }
    });
}

async function saveCategory() {
    const form = document.getElementById('category-form');
    const fd = new FormData(form);
    const name = (fd.get('name') || '').trim();
    if (!name) { Utils.notification.show('请输入分类名称', 'error'); return; }
    const payload = {
        name,
        description: fd.get('description') || '',
        color: fd.get('color') || '#007bff',
        parent_id: fd.get('parent_id') || null,
        sort_order: parseInt(fd.get('sort_order')) || 0,
    };
    const id = fd.get('id');
    const isEdit = !!id;
    try {
        const res = await fetch(isEdit ? `/api/categories/${id}` : '/api/categories', {
            method: isEdit ? 'PUT' : 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        const json = await res.json();
        if (json.success) {
            Utils.notification.show(isEdit ? '分类更新成功' : '分类创建成功', 'success');
            hideCategoryModal();
            await refreshData();
        } else {
            Utils.notification.show(json.message || '保存失败', 'error');
        }
    } catch (e) {
        Utils.notification.show('保存失败，请稍后重试', 'error');
    }
}

function generateSlug(text) {
    return String(text).toLowerCase().replace(/[^\w\s-]/g, '').replace(/[\s_-]+/g, '-').replace(/^-+|-+$/g, '');
}

async function refreshData() {
    await fetchCategories();
    renderParentFilterOptions();
    applyFilters();
}

document.addEventListener('DOMContentLoaded', async () => {
    // Color preset handlers
    const colorPresets = document.querySelectorAll('.color-preset');
    const colorInput = document.getElementById('category-color');
    colorPresets.forEach(preset => {
        preset.addEventListener('click', function() {
            colorInput.value = this.dataset.color;
            colorPresets.forEach(p => p.classList.remove('active'));
            this.classList.add('active');
        });
    });
    colorInput.addEventListener('change', function() { colorPresets.forEach(p => p.classList.remove('active')); });
    document.getElementById('category-modal').addEventListener('click', function(e) { if (e.target === this) hideCategoryModal(); });
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape') hideCategoryModal(); });

    try { await refreshData(); } catch (e) { Utils.notification.show('分类加载失败', 'error'); }
});
</script>
{% endblock %}
